package self.hoy.demo.cloud.order.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import self.hoy.demo.cloud.constant.ApplicationInterface;
import self.hoy.demo.cloud.entities.CommonResult;
import self.hoy.demo.cloud.entities.Payment;
import self.hoy.demo.cloud.order.lb.LoadBalancer;

import javax.annotation.Resource;

/**
 * @author 三共小不
 * @date 2020/5/29
 */
@RestController
@Slf4j
public class OrderController implements ApplicationInterface {

    private static final String PAYMENT_URL = "http://" + PAYMENT_INSTANCE_NAME;
//    private static final String PAYMENT_URL = "http://localhost:8001";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancer loadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> get(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
    }

    @GetMapping("/consumer/payment/ecreate")
    public CommonResult entityCreate(Payment payment) {
        ResponseEntity<CommonResult> c = restTemplate.postForEntity(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
//        return new CommonResult(CommonResult.FAIL,"调试中");
        CommonResult<String> a = c.getBody();
        return a;
    }

    @GetMapping("/consumer/payment/lb/{id}")
    public String loadbalance(@PathVariable("id") Long id) {//ignore null si
        ServiceInstance si = loadBalancer.instances(discoveryClient.getInstances(PAYMENT_INSTANCE_NAME));
        ResponseEntity<CommonResult> result = restTemplate.getForEntity(si.getUri() + "/payment/get/" + id, CommonResult.class);
        log.info(result.getBody().getMessage());
        return result.getStatusCode().toString();
    }
}
